﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using SharedGenomics.Core;
using SharedGenomics.Domain;

namespace SharedGenomics.DataAccess
{
    public class MarkerGenotypeResolver
    {
        public MarkerGenotypeResolver()
        {
            this.MinorAlleles = new Dictionary<string, string>(StringComparer.InvariantCultureIgnoreCase);
        }

        public virtual MarkerGenotype ResolveGenotype(string markerName, string allele1, string allele2)
        {
            markerName.ThrowIfNull("markerName");

            if (allele1.IsEmptyOrWhitespace() || allele2.IsEmptyOrWhitespace())
                return MarkerGenotype.Missing;

            bool isHomogenous = allele1.Equals(allele2, StringComparison.InvariantCultureIgnoreCase);

            //both alleles are non-empty so see if the marker has previously been encountered
            string minorAllele;
            if (this.MinorAlleles.TryGetValue(markerName, out minorAllele))
            {
                if (allele1.Equals(minorAllele, StringComparison.InvariantCultureIgnoreCase))
                {
                    return isHomogenous ? MarkerGenotype.HomozygousMinor : MarkerGenotype.HeterozygousMinorMajor;
                }
                else
                {
                    return isHomogenous ? MarkerGenotype.HomozygousMajor : MarkerGenotype.HeterozygousMajorMinor;
                }
            }
            else
            {
                //take allele1 to be the minor allele
                this.MinorAlleles[markerName] = allele1;
                return isHomogenous ? MarkerGenotype.HomozygousMinor : MarkerGenotype.HeterozygousMinorMajor;
            }
        }

        private IDictionary<string, string> MinorAlleles { get; set; }
    }
}
